import { jsBridge } from './js-tool/jsbridge-tool';
import { jumpHref } from '@/router/jump-href';
import envJudge from '@/lib/judge-env';

// 如果返回的是false说明当前操作系统是手机端，如果返回的是true则说明当前的操作系统是电脑端
const env = envJudge();

// 当前是APP嵌套还是H5跳转
const isApp = ['IOS', 'android'].includes(env);

const DisposeBridge = {
    init(router){
        this.$router = router;
    },
    /**
     * 页面跳转代理，处理  网页跳转/APP跳转
     * @param {Object} payload => {
     *             
     *          url: 跳转地址链接，也可以是跳转路由对象
     *         name: 跳转原生页面，原生标识
     *    options: 设置导航
     *       isBack: 当前是返回操作吗，默认为false,
     *    isRefresh: 返回是否刷新
     *    isReplace: 当前是覆盖历史操作吗，默认为false  例如登录
     *       method: 默认是 goNewPage,   goNewPage|goNativePage / setNativeTitle / toLogin
     *       target: 其余通信方法   miniprogram || newPage  | _self | _blank
     *       data: 额外参数
     *     callback: 回调函数
     */
    /* Creating a variable called relatePage and assigning it the value of a function. */
    /*  */
    relatePage(payload) {
        console.log(payload, '这是relatePage的payload');
        let { name, options = {}, url, isBack, isRefresh, isReplace, method, target, data } = payload;
        
        // 去登录
        if (method == 'toLogin') {
            isApp ? jsBridge.commonJsBridge('tokenExpired') : window.open(jumpHref.login(), '_self');
            return;
        }
        
        // 如果是返回操作
        if (isBack) {
            isApp ? jsBridge.goBack(isRefresh) : this.$router.go(-1);
            return ;
        }
        
        // 如果是设置标题
        if (method === 'setNativeTitle' && isApp) {
            jsBridge.setNativeTitle(options);
            return;
        }

        let targetLink = typeof url == 'object' ? this.$router.resolve(url).href : url;

        if(isApp){
            let _params = {};
            _params.url = targetLink.indexOf('http') > -1 ? targetLink : `${location.protocol}//${window.location.host}${targetLink}`;
            console.log(targetLink, 'location.protocol', location.protocol);
            if(method === 'goBackNativePage') {
                jsBridge.goBackNativePage(name);
            }else{
                jsBridge.goNewPage(target || 'newPage', { ..._params, ...data, ...options });
            }
        } else {
            let _target = target == '_blank' ? '_blank' : '_self'; 
            if (_target == '_blank') { 
                window.open(targetLink, _target);
                return;
            }
            typeof url == 'object' ? this.$router[isReplace ? 'replace' : 'push'](url) : window.open(targetLink, '_self');
        }
    }
}

export default DisposeBridge;

